// 防抖函数
export const debounce = <A extends any[], R>(
  func: (...args: A) => R,
  delay = 1000
): ((...args: A) => void) => {
  let timer: number;
  return function (this: unknown, ...args: A) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
};

// 节流函数
export const throttle = <A extends any[], R>(
  func: (...args: A) => R,
  delay = 1000
): ((...args: A) => void) => {
  let start = +new Date();
  return function (this: unknown, ...args: A) {
    let now = +new Date();
    if (now - start < delay) return;
    start = now;
    func.apply(this, args);
  };
};

// 校验返回的头像能不能正常访问，如果不能显示默认图片
export const checkImageInHtml = (htmlString: string) => {
  return new Promise((resolve) => {
    let imgSrc = "";
    const srcMatch = htmlString.match(/<img.*?src=["'](.*?)["']/);
    // console.log('srcMatch===>', srcMatch)

    if (srcMatch && srcMatch[1]) {
      const imgUrl = srcMatch[1];
      uni.request({
        url: imgUrl,
        method: "GET",
        responseType: "blob", // 确保可以处理图片
        success: (res) => {
          console.log("res111111===>", res);

          if (res.statusCode !== 200) {
            imgSrc = '<img src="/static/img/atvar.png" />';
          } else {
            imgSrc = htmlString;
          }
          resolve(imgSrc); // 请求成功后返回 imgSrc
        },
        fail: (err) => {
          console.log("err===>", err);

          // 处理请求失败的情况
          imgSrc = '<img src="/static/img/atvar.png" />';
          resolve(imgSrc);
        },
      });
    } else {
      // 如果没有匹配到 img src，直接返回原 htmlString
      resolve(htmlString);
    }
  });
};
